﻿//common
function formatAlert(body) {
    var html = '<div class="alert alert-info"><button type="button" class="close" data-dismiss="alert">×</button>' + body + '</div>'
    return html;
}
function displayresult(formid, key, value) {
    if (value.length > 0) {

        $('#' + formid + '-' + key).addClass('error');
        $('#' + formid + '-' + key).find('span.help-inline').text(value);
    } else {
        $('#' + formid + '-' + key).removeClass('error');
        $('#' + formid + '-' + key).find('span.help-inline').text("");
    }
}
function submitFormAjax(form, url) {
    $.ajax({
        type: "POST",
        url: url,
        data: $(form).serialize(), // serializes the form's elements.
        success: function (data) {
            if (data == true) {
                location.reload();
            } else if (data == false) {
            }
            else {
                var formid = $(form).attr('id');
                $.each(data, function (key, value) {
                    displayresult(formid, key, value);
                });


            }
        }
    });
}
function failedstandard(data, form) {
    var formid = $(form).attr('id');
    $.each(data, function (key, value) {
        displayresult(formid, key, value);
    });
}
function submitFormAjaxOption(form, url, success, failed, systemfailed) {
    $.ajax({
        type: "POST",
        url: url,
        data: $(form).serialize(), // serializes the form's elements.
        success: function (data) {
            if (data == true) {
                success();
            } else if (data == false) {
                systemfailed();
            }
            else {
                failed(data, form);
            }
        }
    });
}
function submitFormAjaxOption2(form, url, success, failed, systemfailed) {
    $.ajax({
        type: "POST",
        url: url,
        data: form, // serializes the form's elements.
        success: function (data) {
            if (data == true) {
                success();
            } else if (data == false) {
                systemfailed();
            }
            else {
                failed(data, form);
            }
        }
    });
}
//layout call
$('#shared-changeprofile-btn').click(function (e) {
    e.preventDefault();
    submitFormAjax($('#shared-changeprofile'), '/Personal/SaveProfile');
});
//change password
$('#shared-changepassword-btn').click(function (e) {
    e.preventDefault();
    submitFormAjax($('#shared-changepassword'), '/Personal/SaveAccount');
});
//login
$('#shared-login-btn').click(function (e) {
    e.preventDefault();
    submitFormAjaxOption($('#shared-login'), '/Home/Login', function () {
        location.reload();
    }, failedstandard);
});
function reload() {
    window.location = window.location;
}
function reloadIfDone(data) {
    if (data.percentdone == 100) {
        var btnreload = '<input type="button" value="Hoàn tất xác thực" class="btn" onclick="reload()"/>'
        $('#verifyaccount-info').append(formatAlert("Đã xác thực xong."));
        $('#verifyaccount-info').append(btnreload);
    }
}
//verify email
$('#shared-verifyemail-btn').click(function (e) {
    e.preventDefault();
    submitFormAjaxOption($('#shared-verifyemail'), '/Home/VerifyCode', function () { }, function (data) {
        $('#verifyaccount-email').remove();
        $('#verifyaccount-info').html(formatAlert("Xác thực email thành công."));
        reloadIfDone(data);
    }, function () {
        $('#verifyaccount-info').html(formatAlert("Mã xác thực sai."));
    });
});

//verify email
$('#verifyaccount-email-generatecode').click(function (e) {
    e.preventDefault();
    submitFormAjaxOption(null, '/Home/GenerateVerifyCode', function () {
        $('#verifyaccount-info').html(formatAlert("Mã xác thực đã được gửi."));
    }, function (data) {
    }, function () {
        $('#verifyaccount-info').html(formatAlert("Đã có lỗi xảy ra."));
    });
});
//verify name
$('#shared-verifyname-btn').click(function (e) {
    e.preventDefault();
    submitFormAjaxOption($('#shared-verifyname'), '/Home/VerifyName', function () { }, function (data) {
        $('#verifyaccount-name').remove();
        $('#verifyaccount-info').html(formatAlert("Xác thực tên thành công."));
        reloadIfDone(data);
    }, function () {
        $('#verifyaccount-info').html(formatAlert("Tên bạn sử dụng không đúng."));
    });
});
//verify phone
$('#shared-verifyphone-btn').click(function (e) {
    e.preventDefault();
    submitFormAjaxOption($('#shared-verifyphone'), '/Home/VerifyPhone', function () { }, function (data) {
        $('#verifyaccount-phone').remove();
        $('#verifyaccount-info').html(formatAlert("Xác thực số điện thoại thành công."));
        reloadIfDone(data);
    }, function () {
        $('#verifyaccount-info').html(formatAlert("Số điện thoại không đúng."));
    });
});
//verify fb
$('#verifyaccount-fb-btn').click(function () {
    FB.getLoginStatus(function (response) {
        if (response.status == "connected") {
            $('#fbID').val(response.authResponse.userID);
            FB.api('/me', function (resp) {
                $('#fbname').val(resp.name);
                $('#fbemail').val(resp.email);
                submitFormAjaxOption($('#form-loginFB'), '/Home/VerifyFB', function () { }, function (data) {
                    $('#verifyaccount-fb').remove();
                    $('#verifyaccount-name').remove();
                    $('#verifyaccount-email').remove();
                    $('#verifyaccount-info').html(formatAlert("Xác thực bằng Facebook thành công."));
                    reloadIfDone(data);
                }, function () {
                    $('#verifyaccount-info').html(formatAlert("Facebook Account đã được xác thực cho tài khoản khác."));
                }
                )
            });
        } else {
            FB.login(function (r) {
                if (r.status == 'connected') {
                    localStorage['autologin'] = true;
                    FB.api('/me', function (resp) {
                        $.post('@Url.Action("VerifyFB", "Home")', { fbID: resp.id, fbname: resp.name, fbemail: resp.email }, function (u) {
                            FB.api('/me/viecnho:register', 'post', {
                                account: 'http://samples.ogp.me/535847096482760'
                            }, function (response) {
                                if (response.length > 0 && response != true) {
                                    if (response == false) {
                                        $('#verifyaccount-info').html(formatAlert("Facebook Account đã được xác thực cho tài khoản khác."));
                                    } else {
                                        $('#verifyaccount-fb').remove();
                                        $('#verifyaccount-info').html(formatAlert("Xác thực bằng Facebook thành công."));
                                        reloadIfDone(data);
                                    }
                                }
                                FB.api('/me/picture?width=180&height=180', function (re) {
                                    $.post('@Url.Action("AddFBAvatar", "Home")', { fbID: u.FbID, url: re.data.url }, function (reval) {
                                        window.location = '/' + u.ID;
                                    });
                                });
                            });
                        });
                    });
                }
            }, { scope: 'email,user_status,publish_actions' });
        }
    });
});
$('#verifyaccount-avatar-btn').click(function () {
    document.getElementById('uploadavatar-hidden-file').click();
});
$('#uploadavatar-hidden-file').change(function () {
    var fd = new FormData();

    fd.append("avatarImage", $("#uploadavatar-hidden-file")[0].files[0]);
    $('#shared-waitdialog').modal('show');
    if ($(this).val().length > 0) {
        $.ajax({
            type: "POST",
            url: '/User/UploadAvatar',
            data: fd, // serializes the form's elements.

            processData: false,
            contentType: false,
            success: function (data) {
                $('#shared-waitdialog').modal('hide');
                if (data.percentdone.length > 0) {
                    $('#verifyaccount-avatar').find('.verify-message').html('<span>Verified!</span><br/><img src="' + data.imagePath + '?w=180&h=180&p=90&format=jpg&mode=crop" />');
                    $('#verifyaccount-process').find('.bar').css('width', data.percentdone + '%')
                } else {

                    $('#verifyaccount-avatar').find('.verifyaccount-response').text("Không upload thành công!");
                }
            }
        });

    }
});
//index home
$('#signup-btn').click(function (e) {
    e.preventDefault();
    submitFormAjaxOption($('#signup'), '/User/AddAjax', function () {
        window.location = "/User/GoToUserHome#showverify";
    }, failedstandard);
});
//ajax complete signup
$('#singupstep2-btn').click(function (e) {
    e.preventDefault();
    submitFormAjaxOption($('#singupstep2'), '/Home/CompleteSignup', function () {
        $('#singupstep2-modal').modal('hide');
        location.reload();
    }, failedstandard);
});